package com.bls.productmall.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bls.productmall.entity.Product;
import com.bls.productmall.mapper.ProductMapper;
import com.bls.productmall.service.ProductService;
import com.bls.productmall.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    @Resource
    private ProductMapper productMapper;

    /**
    * 获取产品列表
    */
    @Override
    public R getProductList(int current, int size) {
        List<Product> productList = productMapper.selectList(null);
        int total = productList.size();
        int start = (current-1) * size;
        return R.ok().setMessage("分页查询").setTotal(total).data("productList", productMapper.getProductPage(start, size));
    }

    /**
     * 根据产品名搜索产品
     */
    @Override
    public R getProductByTitle(String title,int current, int size) {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("title", title);
        List<Product> productList = baseMapper.selectList(queryWrapper);
        int total = productList.size();
        int start = (current-1) * size;
        title = "%" + title + "%";
        return R.ok().setMessage("分页查询").setTotal(total).data("productList", productMapper.getProductByTitle(title, start, size));
    }

    /**
    * 增加产品
    */
    @Override
    public int addProduct(Product product) {
        return productMapper.insert(product);
    }

    /**
     * 删除产品
     */
    @Override
    public int deleteProduct(int productId) {
        return productMapper.deleteById(productId);
    }

    /**
     * 更新产品
     */
    @Override
    public int updateProduct(Product product) {
        UpdateWrapper<Product> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", product.getId());
        Product product1 = new Product();
        product1.setTitle(product.getTitle());
        product1.setPrice(product.getPrice());
        return productMapper.update(product1, updateWrapper);  // 第一个参数是新对象，第二个是匹配条件即where
    }
}
